<?php
namespace app\admin\controller;

use think\Config;
use think\File;
use think\Loader;
use think\Request;
use think\Session;
use app\common\controller\Base;
use app\common\model\Language as LanguageModel;


class Language extends Base{

    public function index(){
        $language = LanguageModel::where([])->paginate(50);

        return view('',['language'=>$language]);
    }

    /**
     * 实际上 download表只需要记录 文件的id就行了， 笨蛋。
     * @return \think\response\View
     */
    public function add(){


        return view('',[]);
    }


    public function edit(Request $request){
        $id = $request->param("id");
        $language = LanguageModel::where(['id'=>$id])->find();

        return view('',['language'=>$language]);
    }

    public function create(Request $request){

        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['ckey','desc','content']);
        $data['ckey'] = htmlspecialchars($data['ckey']);
        $data['desc'] = htmlspecialchars($data['desc']);
        $data['content'] = htmlspecialchars($data['content']);

        $res = LanguageModel::create($data);
        if($res){
            $this->success("添加成功");
        }
        $this->error("操作失败");
    }

    /**
     * 删除掉以前的文件 免得浪费空间
     * 这是因为目前还没有做文件的删除功能 所以只能这样做，如果做了可以复用文件，和文件统一管理，那么就不需要这么做了。
     */
    public function update(Request $request){

        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request->only(['id','ckey','desc','content']);
        $data['ckey'] = htmlspecialchars($data['ckey']);
        $data['desc'] = htmlspecialchars($data['desc']);
        $data['content'] = htmlspecialchars($data['content']);

        $res = LanguageModel::where(['id'=>$data['id']])->update($data);

        if($res){
            $this->success("更新成功");
        }
        $this->error("操作失败");
    }


    public function delete(Request $request){
        $id = $request->param('id');

        $res = LanguageModel::where(['id'=>$id])->delete();

        if($res){
            $this->success("删除成功");
        }
        $this->error("操作失败");
    }


    /**
     * 发布语言到配置文件
     */
    public function publish(){
        $config = LanguageModel::where([])->column('ckey,content');
        $config = var_export($config,true);
        $text = '<?php return ';
        $text .= $config;
        $text .= '; ?>';
        $text = htmlspecialchars_decode($text);
        $file = APP_PATH.DS.'index'.DS.'lang'.DS.Config::get('default_lang').'.php';

        //$content = file_get_contents($file);
        file_put_contents($file,$text);
        $this->success("发布成功");
    }



}